package com.mhwx.mhlive.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * 跟App相关的辅助类
 */
public class AppUtils {

    static String parameters = "";
    public static final String USER_SPID = "003_002";
    public static String userId = "";

    public static long systemTime = 0;
    public static final String TIME_START = "1484841600000";
    public static final String TIME_END = "1485964800000";
    public static List<List<String>> childList = new ArrayList<List<String>>();
    public static List<String> commonList = new ArrayList<String>();
    //图片缓存地址
    public static final String IMAGE_CACHE_PATH = "sdcard/Android/data/dianyingCache";

    private AppUtils() {
        /**cannot be instantiated **/
        throw new UnsupportedOperationException("cannot be instantiated");

    }

    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            // 当前应用的版本名
            String versionName = info.versionName;
            // 当前版本的版本号
            int versionCode = info.versionCode;
            // 当前版本的包
            String packageNames = info.packageName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 获取WebView User-Agent(用户代理值)
     */
    public static String getUserAgent(Context context) {
        WebView webview;
        webview = new WebView(context);
        webview.layout(0, 0, 0, 0);
        WebSettings settings = webview.getSettings();
        String ua = settings.getUserAgentString();
        return ua;
    }

    /**
     * 获取移动设备所处内网ip
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("Wifi IpAddress", ex.toString());
        }
        return null;
    }

    /**
     * 获取ANDROID_ID
     */
    public static String getAndroidId(Context context) {
        String androidId;
        androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    /**
     * 获取app版本号
     */
    public static String getAppVersion(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            String versionName = info.versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取应用程序名称
     */
    public static String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (PackageManager.NameNotFoundException e) {
            Logger.e(e.getMessage(), e);
        }
        return "";
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            Logger.i("AppUtils" + e.getMessage(), e);
        }
        return "";
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            Logger.i("AppUtils" + e.getMessage(), e);
        }
        return 0;
    }

    /**
     * 获取应用程序的IMEI号
     */
    public static String getDeviceId(Context context) {
        try {
            TelephonyManager telecomManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String imei = telecomManager.getDeviceId();
            return imei;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取手机设备的系统版本号
     */
    public static String getDeviceSysVersion() {
        try {
            String version = android.os.Build.VERSION.RELEASE;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            Logger.i("AppUtils" + e.getMessage(), e);
        }
        return "";
    }

    /**
     * 获取设备的型号
     */
    public static String getDeviceModel() {
        try {
            String model = android.os.Build.MODEL;
            return model;
        } catch (Exception e) {
            e.printStackTrace();
            Logger.i("AppUtils" + e.getMessage(), e);
        }
        return "";
    }

    /**
     * 获取设备制造商
     */
    public static String getDeviceManufacturer() {
        try {
            String deviceName = android.os.Build.MANUFACTURER;
            return deviceName;
        } catch (Exception e) {
            e.printStackTrace();
            Logger.i("AppUtils" + e.getMessage(), e);
        }
        return "";
    }





    private static final String CHANGE_TAG = "cztchannel_";

    /**
     * 从apk中获取版本信息
     *
     * @param context
     * @return
     */
    public static String getChannelFromApk(Context context) {
        //从apk包中获取
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        //注意这里：默认放在meta-inf/里， 所以需要再拼接一下
        String key = "META-INF/" + CHANGE_TAG;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith(key)) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            Logger.e(e, e.getMessage());
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (BuildConfig.DEBUG) {
                ret = "cztchannel_cnlive";
            }
        }
        String[] split = ret.split("_");
        String channel = "";
        if (split != null && split.length >= 2) {
            channel = ret.substring(split[0].length() + 1);
        }
        Logger.e("frmId:" + channel);
        return channel;
    }

    private static String getMac() {
        String macSerial = null;
        String str = "";

        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return macSerial;
    }

    /**
     * 获取公共参数
     */
    public static String getCommonParameters(Context context) {
        try {
            String deviceSysVersion = AppUtils.getDeviceSysVersion();
            String appVersion = AppUtils.getAppVersion(context);
            String deviceModel = AppUtils.getDeviceModel();
            String deviceManufacturer = AppUtils.getDeviceManufacturer();
            String deviceId = AppUtils.getDeviceId(context);
            String appId = "shoujimovie";
            String deviceSysType = "ANDROID";
            int appCode = AppUtils.getVersionCode(context);
            String uid = AppUtils.userId;
            String appChannel = getChannelFromApk(context);
            String mac = AppUtils.getMac();
            parameters = "?deviceSysVersion=" + deviceSysVersion + "&" + "appVersion=" + appVersion + "&" + "deviceModel=" + deviceModel + "&" + "deviceManufacturer=" + deviceManufacturer + "&" + "deviceId=" + deviceId + "&" + "appId=" + appId + "&" + "deviceSysType=" + deviceSysType + "&" + "appChannel=" + appChannel + "&" + "appCode=" + appCode + "&" + "userId=" + uid + "&"  + "&" + "mac=" + mac;
            return parameters;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取公共参数
     */
    public static String getParameters(Context context) {
        try {
            String deviceSysVersion = AppUtils.getDeviceSysVersion();
            String appVersion = AppUtils.getAppVersion(context);
            String deviceModel = AppUtils.getDeviceModel();
            String deviceManufacturer = AppUtils.getDeviceManufacturer();
            String deviceId = AppUtils.getDeviceId(context);
            String appId = "shoujimovie";
            String deviceSysType = "ANDROID";
            int appCode = AppUtils.getVersionCode(context);
            String uid = AppUtils.userId;
            String appChannel = getChannelFromApk(context);
            parameters = "&deviceSysVersion=" + deviceSysVersion + "&" + "appVersion=" + appVersion + "&" + "deviceModel=" + deviceModel + "&" + "deviceManufacturer=" + deviceManufacturer + "&" + "deviceId=" + deviceId + "&" + "appId=" + appId + "&" + "deviceSysType=" + deviceSysType + "&" + "appChannel=" + appChannel + "&" + "appCode=" + appCode + "&" + "userId=" + uid ;
            return parameters;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * json解析方法
     *
     * @param json
     * @param clazz 对象的字解码文件
     * @return 解析出来的对象
     */
    public static <T> T jsonToBean(String json, Class<T> clazz) {
        Gson gson = new Gson();
        return gson.fromJson(json, clazz);
    }

    //判断是都安装了微信
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    //判断是都安装了支付宝
    public static boolean isAliPayAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.eg.android.AlipayGphone")) {
                    return true;
                }
            }
        }
        return false;
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
}


